//
//  WBNetWorkManager+Extension.swift
//  mySwiftVV
//
//  Created by hu yr on 2016/12/17.
//  Copyright © 2016年 terry. All rights reserved.
//

import Foundation

// MARK: - 封装新浪微博的网络请求方法
extension WBNetWorkManager{
    
    /// 加载微博数据字典数组
    ///
    /// - Parameters:
    ///   - since_id: 则返回ID比since_id大的微博（即比since_id时间晚的微博），默认为0。
    ///   - max_id: 返回ID小于或等于max_id的微博，默认为0。
    ///   - completion: 完成后的回调 [list: 微博字典数组/是否成功]

    func statusList(since_id: Int64 = 0,max_id: Int64 = 0, completion : @escaping ([[String : AnyObject]]?, _: Bool) -> ()){
        
        let urlSring = "https://api.weibo.com/2/statuses/home_timeline.json"
        
//        let params = ["access_token" : "2.00l9SUaD0aZKw5826950c15eaLL1IB"]
        //2.00l9SUaD0aZKw5826950c15eaLL1IB
        
        
        let param = ["since_id": "\(since_id)",
            "max_id": "\(max_id > 0 ? max_id - 1 : 0)"]
        
        
        tokenRequest(URLString: urlSring, parameters: param) { (json, isSuccess) in
            
//            print(" ---> \(json)")
            //从json中获取 statuses 字典数组
            //            //如果 as? 失败, result = nil
            //提示:服务器返回的字典数组,就是按照时间的倒序排序的
            let dict = json as? [String : AnyObject]
            
            
            let result = dict?["statuses"] as? [[String : AnyObject]]
            
            completion(result,isSuccess)
            
        }
        
    }
    
    /// 返回微博的未读数量
    func unreadCount(completion:@escaping (_ count: Int)->()){
        
        guard let uid = userAccount.uid else {
            
            return
        }
        
        let urlString = "https://rm.api.weibo.com/2/remind/unread_count.json"
        
        let params = ["uid" : uid]
        
        tokenRequest(URLString: urlString, parameters: params) { (json, isSucess) in
            
//            print(json as Any)
            
            let dict = json as? [String : AnyObject]
            
            let count = dict?["status"] as? Int
            
            completion(count ?? 0)
            
        }
        
    }
    
}
// MARK: - 用户信息
extension WBNetWorkManager{
    /// 加载 当前用户信息 - 用户登录后,立即执行
    func loadUserInfo(completion: @escaping (_ dict:[String : AnyObject])->()){
        guard let uid = userAccount.uid else {
            
            return
        }
        let urlString = "https://api.weibo.com/2/users/show.json"
        
        let params = ["uid":uid]
        
        tokenRequest(URLString: urlString, parameters: params) { (json, isSuccuess) in
            
//            print(json as Any)
            completion(json as? [String : AnyObject] ?? [:] )
        }
        
    }
}
// MARK: - OAuth相关方法
extension WBNetWorkManager{
    
    /// 加载accessToken方法
    func loadAccessToken(code : String, completion: @escaping (_ isSuccess: Bool) -> ()){
        let urlString = "https://api.weibo.com/oauth2/access_token"
        
        let params = ["client_id":WBAppKey,
                      "client_secret":WBAppSecret,
                      "grant_type":"authorization_code",
                      "code":code,
                      "redirect_uri":WBRedirectURI]
        
        // 发起网络请求
        request(method: .POST, URLString: urlString, parameters: params) { (json, isSuccess) in
            
//            print(json as Any)
            self.userAccount.yy_modelSet(with: json as? [String : AnyObject] ?? [:])
            
            print(self.userAccount)
            
            
            
            //加载当前用户信息
            self.loadUserInfo(completion: { (json) in
                print(json)
                
                //使用用户信息字典设置用户账户信息(昵称和头像地址)
                self.userAccount.yy_modelSet(with: json)
                
                //保存模型
                self.userAccount.saveAccount()
                
                print(self.userAccount)
                
                // 用户信息加载完成后 ,完成回调
                completion(isSuccess)
            })
            
            
        }
        
    }
    
}
